//获取登录用户名
var rename = tool.getCookie('rename')
var user_name = tool.getCookie("username")
if(rename || user_name){
    var res = rename || user_name
    $(".nav .a_login").css("display","none").next().css("display","none")
    $(".nav .a_register").css("display","none").next().css("display","none")
    $(".user_box").css("display","block")
    $(".user_id").text(res)
}else{
    layer.msg("请先登录您的账户",{
        icon:2,
        time:1500
    },function(){
        localStorage.setItem("url",location.href);
        location.href="./login.html"
    })
}
$(".exit").click(function(){
    tool.setCookie('rename',$('#usname').val(),-1000)
    tool.setCookie('username',$('#usname').val(),-1000)
    location.href="./shopping.html"
})
$(".nav .a_login").click(function(){
    localStorage.setItem("url",location.href)
    location.href="./login.html"
})
$(".a_register").click(function(){
    location.href="./register.html"
})
//历史记录
$.ajax({
    url:"./php/getHistory.php",
    data:{res},
    dataType:"json",
    success:res=>{
        var {data}=res;
        data = data.sort(function(a,b){
            return b.Id-a.Id
        }).slice(0,4);
        console.log(data)
        data.forEach(item=>{
            var ids=item.goodsid
            var str =  "";
            $.ajax({
                url:"../php/shopping.php",
                data:{ids},
                dataType:"json",
                success(res){
                    var {data}=res;
                    console.log(data);
                    for(var i=0;i<data.length;i++){
                        console.log(data[i].price);
                        str += `
                        <dl>
                            <dt><img src="${data[i].img}" alt=""></dt>
                            <dd><p>${data[i].name}</p><img src="./images/cart04.png" alt=""></dd>
                        </dl>
                        `
                    }
                    $(".dl_box").append(str);
                    layer.close(loadindex);
                }
            })
        })
        
        
    }
})
$.ajax({
    url:"./php/getHot.php",
    data:{res},
    dataType:"json",
    success:res=>{
        var {data}=res;
        data = data.sort(function(a,b){
            return b.readnum-a.readnum
        }).slice(0,4);
        console.log(data)
        var str02="";
        for(var i=0;i<data.length;i++){
            str02 += `
            <dl>
                <dt><img src="${data[i].img}" alt=""></dt>
                <dd><p>${data[i].name}</p><img src="./images/cart04.png" alt=""></dd>
            </dl>
            `
        }
        $(".dl_box1").html(str02)
    }
})

var loadindex = layer.load(1,{
    shade: [0.5,'#666']
})
console.log(1)
var str = localStorage.getItem("cartData");
console.log(str)
if(str){
    var arr = JSON.parse(str);
    arr = arr.filter(item=>item.username === res);
    if(arr.length){
        console.log(arr);
        var ids = arr.map(item=>item.id).join(",");
        console.log(ids)
        $.ajax({
            url:"./php/shopping.php",
            data:{ids},
            dataType:"json",
            success(res){
                var {data}=res;
                console.log(data);
                var str03 =  "";
                for(var i=0;i<data.length;i++){
                    var number=arr.find(item=>item.id === data[i].id).number;
                    console.log(data[i].price);
                    console.log(number)
                    str03 += `
                        <div class="item">
                            <div class="select_all">
                                <input type="checkbox" name="select">
                            </div>
                            <div class="item_info">
                                <img src="${data[i].img}" alt="">
                                <a href="" title="${data[i].name}">${data[i].name}</a>
                            </div>
                            <div class="item_price">
                            ￥<span class="price">${data[i].price}</span>
                            </div>
                            <div class="item_num"><span class="dec">-</span><input class="num" min="1" max="${data[i].stock}" value="${number}"><span class="add">+</span></div>
                            <div class="item_total" data-id="${data[i].id}">
                            ￥<span class="t_price">${(data[i].price*number).toFixed(2)}</span>
                            </div>
                            <div class="item_delete">删除</div>
                        </div>
                    `
                }
                $(".list").html(str03);
                
                selectAll()
                select()
                addOrDec()
                subtotal()
                total()
                removeCart()
                clearAll()
            }
        })
    }else{
        layer.close(loadindex);
        empty()
    }
}else{
    layer.close(loadindex);
    empty()
}
function empty(){
    $(".m_inner").html(`
        <div class="null"><img src="./images/shopping.png"><h1>购物车空空的哦~，去看看心仪的商品吧~</h1><a href="./index.html">去购物</div>
    `)
};
function selectAll(){
    $("[name='select_all']").click(function(){
        $("[type='checkbox']").prop("checked",$(this).prop("checked"))
        total()
    })
   
}
 function select(){
     console.log($("[name='select']"))
     $("[name='select']").click(function(){
         console.log(1)
         var arr = Array.prototype.slice.call($("[name='select']"));
         var bool = arr.every(item=>item.checked);
         $("[name='select_all']").prop("checked",bool);
         total()
     })
 }
function subtotal(){
    $(".item").each((index,item)=>{
        var price = $(item).children(".item_price").children(".price").text()-0;
        // console.log($(item).children(".item_price").children(".price"));
        var number = $(item).children(".item_num").children(".num").val()-0;
        // console.log(number);
        var sub = (price*number).toFixed(2);
        $(item).children(".item_total").children(".t_price").text(sub);
    })
}
function total(){
    var totalnum=0;
    var totalprice=0;
    $('[name="select"]:checked').each((index,item)=>{
        totalnum+=$(item).parent().parent().children(".item_num").children(".num").val()-0;
        totalprice+=$(item).parent().parent().children(".item_total").children(".t_price").text()-0;
        console.log($(item).parent().parent().children(".item_total").children(".t_price").text())
    })
    console.log(totalprice)
    $('.total_number').text(totalnum);
    $('.total_price').text(totalprice.toFixed(2));
}
function addOrDec(){
   $(".dec").click(function(){
       var number=$(this).next().val()-0;
       number--;
       if(number<=1){
           number=1;
       }
       $(this).next().val(number);
       var data = JSON.parse(localStorage.getItem("cartData"));
       var id = $(this).parent().next().attr("data-id");
       var currentData = data.find(item=>item.username === res && item.id == id);
       currentData.number = number;
       localStorage.setItem("cartData",JSON.stringify(data))
       subtotal()
       total()
   }) 
   $(".add").click(function(){
    var number=$(this).prev().val()-0;
    number++;
    if(number>=$(this).prev().attr("max")){
        number=$(this).prev().attr("max");
    }
    $(this).prev().val(number);
    var data = JSON.parse(localStorage.getItem("cartData"));
    var id = $(this).parent().next().attr("data-id");
    var currentData = data.find(item=>item.username === res && item.id == id);
    console.log(id)
    currentData.number = number;
    localStorage.setItem("cartData",JSON.stringify(data))
    subtotal()
    total()
}) 
}
function removeCart(){
    $(".item_delete").click(function(){
        var that =$(this)
        layer.confirm("你确定要删除该商品吗？",{
            btn:["确定","我再看看"]
        },function(){
            that.parent().remove()
            var arr = JSON.parse(localStorage.getItem('cartData'))
            var id = $(".item_total").attr('data-id')
            var index = arr.findIndex(item=>item.id == id && item.username === res)
            arr.splice(index,1)
            localStorage.setItem('cartData',JSON.stringify(arr))
            layer.msg('删除成功',{
                icon:1,
                time:1500
            })
            arr = JSON.parse(localStorage.getItem('cartData'))
            var data = arr.filter(item=>item.username === res)
            if(!data.length){
                empty()
            }
        },function(){
            layer.msg('那就再看看吧~',{
                icon:1,
                time:1500
            })
        })
    })
}
function clearAll(){
    $(".p3").click(function(){
        var that=$(this)
        layer.confirm("你确定要删除该商品吗？",{
            btn:["确定","我再看看"]
        },function(){
            that.parent().remove()
            var arr = JSON.parse(localStorage.getItem('cartData'))
            var id = $(".item_total").attr('data-id')
            var index = arr.findIndex(item=>item.username === res)
            while(index!=-1){
                console.log(111)
                arr.splice(index,1)
                localStorage.setItem('cartData',JSON.stringify(arr))
                index = arr.findIndex(item=>item.username === res)
                console.log(index)
            }
            layer.msg('清空成功',{
                icon:1,
                time:1500
            })
            arr = JSON.parse(localStorage.getItem('cartData'))
            var data = arr.filter(item=>item.username === res)
            if(!data.length){
                empty()
            }
        },function(){
            layer.msg('那就再看看吧~',{
                icon:1,
                time:1500
            })
        })
    })
}